package org.apache.click.doubleclick.inject;

import org.apache.click.Context;
import org.apache.click.Page;
import org.apache.click.PageInterceptor;
import org.apache.commons.lang.Validate;

import javax.servlet.ServletContext;

/**
 * Page interceptor to inject dependencies
 *
 * @author Jahid Shohel(development.jsh@gmail.com)
 */
public class DependencyInjectorPageInterceptor implements PageInterceptor {

    private DependencyInjector dependencyInjector;
    public static final String DEPENDENCY_INJECTOR = "currentDependencyInjector";

    public DependencyInjectorPageInterceptor() {
        Validate.isTrue(Context.hasThreadLocalContext(), "Thread local context is not available");
        ServletContext servletContext = Context.getThreadLocalContext().getServletContext();
        Validate.notNull(servletContext, "Servlet context is null");
        Validate.notNull(servletContext.getAttribute(DEPENDENCY_INJECTOR), "No dependency injector found on servlet context.");
        dependencyInjector = (DependencyInjector) servletContext.getAttribute(DEPENDENCY_INJECTOR);
    }

    @Override
    public boolean preCreate(Class<? extends Page> aClass, Context context) {
        return true;
    }

    @Override
    public boolean postCreate(Page page) {
        dependencyInjector.injectDependencies(page);
        return true;
    }

    @Override
    public boolean preResponse(Page page) {
        return true;
    }

    @Override
    public void postDestroy(Page page) {
    }
}